package com.kaka.bus.engine;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.kaka.bus.R;
import com.kaka.bus.adapter.HomePageAdapter;
import com.kaka.bus.base.BaseActivity;
import com.kaka.bus.bean.AppInfo;
import com.kaka.bus.bean.HttpWrapper;
import com.kaka.bus.bean.MyInfo;
import com.kaka.bus.bean.TabEntity;
import com.kaka.bus.bean.Version;
import com.kaka.bus.constant.Constant;
import com.kaka.bus.down.bean.Download;
import com.kaka.bus.down.service.DownloadService;
import com.kaka.bus.down.utils.StringUtils;
import com.kaka.bus.engine.home.info.InfoFragment;
import com.kaka.bus.engine.home.main.MainFragment2;
import com.kaka.bus.engine.user.login.LoginActivity;
import com.kaka.bus.listener.Listener;
import com.kaka.bus.util.StatusBarUtil;
import com.kaka.bus.util.ToastUtil;
import com.kaka.bus.util.U;
import com.kaka.bus.view.NoScrollViewPager;
import com.kaka.bus.view.dialog.TempletDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.youth.banner.WeakHandler;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by zhangqi on 2017/12/20.
 * e-mail : ${email}
 * desc :
 */

public class HomeActivity extends BaseActivity<HomePresenter> implements HomeContract.View {

    @BindView(R.id.home_vp)
    NoScrollViewPager mHomeVp;
    @BindView(R.id.home_tab)
    CommonTabLayout mHomeTab;

    private static final int REQUEST_CODE_UPDATE = 20;

    private ArrayList<CustomTabEntity> mTabData = new ArrayList<>();

    private List<Fragment> mFramentList = new ArrayList<>();

    private String[] mTabName = {"首页", "我的"};

    private int[] mTabIconNormal = {R.mipmap.home_linq_normal, R.mipmap.home_wode_normal};
    private int[] mTabIconSelect = {R.mipmap.home_jiekuan_icon_press, R.mipmap.home_wode_dianji_press};
    public int mStatus;
    private long exitTime;
    WeakHandler weakHandler;
    /**
     * 下载地址
     */
    private String mDownloadUrl;
    /**
     * 是否强制更新
     */
    private boolean mIsUpdate;
    private Intent mIntent;
    private RxPermissions mRxPermissions;

    /**
     * 更新框
     */
    private TempletDialog mVersionDialog;
    private TextView mMDialogVersionTv;

    @Override
    protected void initView() {
        super.initView();
        EventBus.getDefault().register(this);
        mRxPermissions = new RxPermissions(this);
        StatusBarUtil.setTranslucentForImageViewInFragment(HomeActivity.this, null);
        mStatus = StatusBarUtil.StatusBarLightMode(this);
        weakHandler = new WeakHandler();
        for (int i = 0; i < mTabName.length; i++) {
            mTabData.add(new TabEntity(mTabName[i], mTabIconSelect[i], mTabIconNormal[i]));
        }

        mHomeTab.setTabData(mTabData);

        mFramentList.add(MainFragment2.getInstance(null));
        mFramentList.add(InfoFragment.getInstance(null));

        mHomeVp.setAdapter(new HomePageAdapter(getSupportFragmentManager(), mFramentList));
        mHomeVp.setOffscreenPageLimit(3);
        mHomeVp.setScroll(false);

    }


    @Override
    protected void onStart() {
        super.onStart();

        if (mVersionDialog == null || !mVersionDialog.isShowing()) {
            AppInfo appInfo = U.getAppInfo(this);
            mPresenter.checkVersion(Constant.PLATFORM, appInfo.getVersionName());
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void initListener() {
        mHomeTab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                if ((position == 1) && TextUtils.isEmpty(getUserId())) {
                    mHomeTab.setCurrentTab(0);
                    startActivity(new Intent(HomeActivity.this, LoginActivity.class));
                } else {
                    mHomeVp.setCurrentItem(position, false);
                }
            }

            @Override
            public void onTabReselect(int position) {
            }
        });

        mHomeVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                mHomeTab.setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    public void toHome() {
        mHomeTab.setCurrentTab(0);
        mHomeVp.setCurrentItem(0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtil.showShort(this, "再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_home;
    }

    @Override
    public void onNetChange(boolean isConnect) {
        super.onNetChange(isConnect);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mIntent != null) {
            stopService(mIntent);
        }
        EventBus.getDefault().unregister(this);
    }

    //检查更新
    @Override
    public void checkOk(HttpWrapper<Version> data) {
        Version version = data.getData();

        if (version != null) {
            mDownloadUrl = version.getDownloadUrl();
        }

        if (Constant.SUCCESS_CODE.equals(data.getCode())) {
            if (version.getHaveNewVersion() == 1) {
                //需要更新
                if (version.getForceUpdate() == 1) {
                    mIsUpdate = true;
                } else if (version.getForceUpdate() == 0) {

                }

                //需要更新
                toUpdate();
            } else if (version.getHaveNewVersion() == 0) {
                //不需要更新
            }
        } else if ("203".equals(data.getCode())) {
            mIsUpdate = true;
            //需要更新
            toUpdate();
        } else {
            /**
             * 不需要更新
             */
        }
    }

    /**
     * 创建更新
     */
    private void toUpdate() {
        if (mIsUpdate) {
            U.getSingleDialog(this, "提示", "当前版本较低,点击升级版本!", "升级", this::downloadApk).show();
        } else {
            U.getSlectDialog(this, "提示", "当前版本较低,点击升级版本!", "暂不升级", "升级", new Listener.OnNormalAlertDialogChooseClickListener() {
                @Override
                public void onLeft() {
                }

                @Override
                public void onRight() {
                    downloadApk();
                }
            }).show();
        }
    }


    public void downloadApk() {
        addSubscription(mRxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        mIntent = new Intent(HomeActivity.this, DownloadService.class);
                        mIntent.putExtra("url", mDownloadUrl);
                        startService(mIntent);

                        mVersionDialog = new TempletDialog.Builder(this)
                                .setLayout(R.layout.dialog_version).setWidthPer(0.6).setMoveY(0)
                                .setWindowAnim(R.style.person＿dialog_anim).build();
                        mVersionDialog.setCancelable(false);
                        mVersionDialog.setCanceledOnTouchOutside(false);
                        mVersionDialog.show();
                        mMDialogVersionTv = mVersionDialog.findViewById(R.id.dialog_version_tv);
                    } else {
                        finish();
                    }
                }));
    }

    /**
     * 下载进度的展示
     *
     * @param myInfo
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void downInfo(MyInfo<Download> myInfo) {
        if (myInfo.getType() == MyInfo.MyInfoEnum.downinfo) {
            Download download = myInfo.getData();

            if (mMDialogVersionTv.getVisibility() != View.VISIBLE) {
                mMDialogVersionTv.setVisibility(View.VISIBLE);
            }

            if (download.getProgress() == 100) {
                mMDialogVersionTv.setText("下载完成");
            } else {
                mMDialogVersionTv.setText(U.connectString(StringUtils.getDataSize(download.getCurrentFileSize()),
                        "/", StringUtils.getDataSize(download.getTotalFileSize())));
            }
        } else if (myInfo.getType() == MyInfo.MyInfoEnum.downerror) {
            U.getSingleDialog(this, "提示", "下载失败,请去应用宝更新本软件以继续使用", "确定",
                    () -> {
                        finish();
                    }).show();
        }
    }

    /**
     * 下载完成
     *
     * @param myInfo
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void downOver(MyInfo<File> myInfo) {
        if (myInfo.getType() == MyInfo.MyInfoEnum.installApp) {
            installApk(myInfo.getData());
        }
    }

    /**
     * 安装apk
     *
     * @param file
     */
    protected void installApk(File file) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        /**
         * 适配android7.0
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(this, Constant.PACKAGE + ".fileprovider", file);
            intent.setDataAndType(contentUri,
                    "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
        }
        startActivityForResult(intent, REQUEST_CODE_UPDATE);

        weakHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        }, 500);


    }
}
